package com.bing.services;

import com.bing.HUtils;
import com.bing.entity.Account;
import com.bing.entity.Status;
import org.hibernate.Query;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * Created by kaibb on 15-11-1.
 */
public class AccountServicesImpl implements AccountServices {
    private static final Logger LOGGER = LoggerFactory.getLogger(AccountServicesImpl.class);


    @Override
    public  void saveMySqlAccounts(List<Account> accounts) {
        if (accounts.size() == 0) {
            return;
        }
        Session session = HUtils.getMySqlSession();
        session.beginTransaction();
        for (Account account : accounts) {
            Object uid = session.createQuery("from Account a where a.uid = :uid ").setParameter("uid", account.getUid()).uniqueResult();
            if (null == uid) {
                session.save(account);
            }
        }
        session.flush();
        session.clear();
        session.getTransaction().commit();

        session.close();
    }

    @Override
    public void updateAccounts(List<Account> accounts) {
        Session session = HUtils.getMySqlSession();
        session.beginTransaction();
        for (Account account : accounts) {
            session.update(account);
        }
        session.flush();
        session.clear();
        session.getTransaction().commit();

        session.close();
    }


    @Override
    public List<Account> getAccounts(int size) {
        Session session = HUtils.getMySqlSession();
        session.beginTransaction();
        Query query = session.createQuery("from Account where status in (:status)");
        query.setParameterList("status", new Status[]{Status.INIT,Status.TIMEOUT});
        query.setMaxResults(size);
        List list = query.list();
        session.flush();
        session.clear();
        session.getTransaction().commit();
        session.close();
        return list;
    }
}
